import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class DAY0316 {
    public int maxProfit(int[] prices) {
        int min=Integer.MAX_VALUE;
        int max=0;
        for (int i = 0; i < prices.length; i++) {
            if(min>prices[i]){
                min=prices[i];
            }else if (max<prices[i]-min){
                max=prices[i]-min;
            }
        }
        return max;
    }


    public int[] intersect(int[] nums1, int[] nums2) {
        if(nums1.length>nums2.length){
            return intersect(nums2,nums1);
        }
        Map<Integer,Integer> map=new HashMap<Integer,Integer>();
        for (int num:nums1) {
            int count=map.getOrDefault(num,0)+1;
            map.put(num,count);
        }
        int[] nums3=new int[nums1.length];
        int index=0;
        for (int num:nums2) {
            int count=map.getOrDefault(num,0);
            if(count>0){
                nums3[index++]=num;
                count--;
                if(count>0){
                    map.put(num,count);
                }else {
                    map.remove(num);
                }
            }
        }
        return Arrays.copyOfRange(nums3,0,index);
    }

    public boolean isPerfectSquare(int num) {
        int left=0;
        int right=num;
        while(left<=right){
            int mid=(right-left)/2+left;
            long n=(long)mid*mid;
            if(n>num){
                right=mid-1;
            } else if (n<num) {
                left=mid+1;
            }else {
                return true;
            }
        }
        return false;
    }

    public int findTheDistanceValue(int[] arr1, int[] arr2, int d) {
        int cnt=0;
        for(int i:arr1){
            boolean ok=true;
            for (int j:arr2){
                ok&=Math.abs(i-j)>d;
            }
            cnt+=ok?1:0;
        }
        return cnt;
    }



    public String replaceSpace(String s) {
        int n=s.length();
        char[] s1=new char[n*3];
        int size=0;
        for(int i=0;i<n;i++){
            char c=s.charAt(i);
            if(c==' '){
                s1[size++]='%';
                s1[size++]='2';
                s1[size++]='0';
            }else{
                s1[size++]=c;
            }
        }
        String news2=new String(s1,0,size);
        return news2;
    }



}
